const {exec}=require("../db")
const md5=require('md5');
const { json } = require("express");
var jwt = require('jsonwebtoken');
class User{
    async login(req,res){
        const {username,password}=req.body;
        let sql=`select id,username,phone,sex,age,address from users where username=? and password=?`
        let params=[username,md5(password+'md5')]
        try {
            const results=await exec(sql,params);
            if(results.length>=1){
                res.json({msg:'登录成功',data:results[0],token:jwt.sign({...results[0]},'asus'),code:200})
            }else {
                res.json({msg:'登录失败2',code:404})
            }
        } catch (error) {
            res.json({msg:'登录失败1',code:404})
        }
    }

    async add(req,res){
        let {username,password,phone,sex,age,address}=req.body;
        if(username==undefined||password==undefined){
            res,json({msg:'数据错误',code:404})
            return;
        }
        if(phone==undefined||phone=='')phone=null
        if(address==undefined||address=='')address=null
        if(sex==undefined||sex=='')sex=null
        if(age==undefined||age=='')age=null
        
        let sql=`insert into users (username,password,phone,sex,age,address) value 
        (?,?,?,?,?,?)`
        let params=[username,md5(password+'md5'),phone,sex,age,address];
        try {
            const results=await exec(sql,params)
            if(results.affectedRows>=1){
                res.json({msg:'注册成功',code:200})
            }else {
                res.json({msg:'注册失败2',code:404})
            }
        } catch (error) {
            res.json({msg:'用户名已经注册',code:404})
        }

    }

    async isLogin(req,res){
        let token=req.get('token');
        try {
            let data=jwt.verify(token,'asus');
            let num=await exec(`SELECT COUNT(*) as num FROM cart WHERE uid=?`,[data.id])
            res.json({user:data,num:num[0].num,code:200});
        } catch (error) {
            res.json({code:401});
        }
    }
}


module.exports=new User